package com.ideafactory.client.utils.power;

import android.content.Intent;
import android.os.Build;
import android.util.Log;

import com.ideafactory.client.afinal.NetConstants;
import com.ideafactory.client.utils.FileConstants;
import com.ideafactory.client.utils.HeartBeatClient;
import com.ideafactory.client.utils.caches.ACache;
import com.ideafactory.client.utils.netutils.MyCallBack;
import com.ideafactory.client.utils.netutils.NetUtils;
import com.ideafactory.client.ybservice.APP;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class PowerOffTool {

	private static final String TAG = "PowerOffTool";
	private static PowerOffTool powerOffTool = null;

	private PowerOffTool() {
	}

	public static PowerOffTool getPowerOffTool() {
		if (powerOffTool == null) {
			synchronized (PowerOffTool.class) {
				if (powerOffTool == null) {
					powerOffTool = new PowerOffTool();
				}
			}
		}
		return powerOffTool;
	}

	public static final String POWER_ON = "poerOn";
	public static final String POWER_OFF = "poerOff";

	/**
	 * 获取开关机时间
	 * @param uid
	 * 设备id
	 */
	public static void getPowerOffTime(String uid) {
		Map map = new HashMap();
		map.put("uid", uid);

		Log.e("uid","uid-------->"+uid);
		NetUtils.Post(NetConstants.POWER_OFF_URL, map, new MyCallBack<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("时间", "" + "");
				handResults(result);
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				super.onError(ex, isOnCallback);

				Log.e(TAG, "onError------------->"+ex.getMessage());
			}
		});
	}


	/**
	 * 获取开关机时间
	 * @param uid
	 * 设备id
	 */
	public static void getPowerOffTimeRestart(String uid) {
		Map map = new HashMap();
		map.put("uid", uid);
		NetUtils.Post(NetConstants.POWER_OFF_URL, map, new MyCallBack<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("时间",""+"");
				handResults(result);
				//重启一下机器
				Log.e("机器重启", "restart");
				PowerOffTool.restart();
			}

		});
	}

	private static void handResults(String powerOffJson) {
		powerOffJson = powerOffJson.replaceAll("\\\\", "");
		if (powerOffJson.startsWith("\"")) {
			powerOffJson = powerOffJson.substring(1, powerOffJson.length() - 1);
		}
		JSONTokener jsonParser = new JSONTokener(powerOffJson);
		try {
			// 开机字符串
			String powerOn = "";
			// 关机字符串
			String powerOff = "";
			JSONArray person = (JSONArray) jsonParser.nextValue();
			for (int i = 0; i < person.length(); i++) {
				JSONObject jsonObject = (JSONObject) person.get(i);
				Integer status = jsonObject.getInt("status");
				Integer runType = jsonObject.getInt("runType");
				String runDate = jsonObject.getString("runDate");
				if (runDate.indexOf(":") != -1) {
					runDate = runDate.substring(runDate.indexOf(":") + 1, runDate.length());
				}
				String runTime = jsonObject.getString("runTime");
				if (runType == 0 && status == 0) {
					powerOn = runDate + ";" + runTime;
				} else if (runType == 1 && status == 0) {
					powerOff = runDate + ";" + runTime;
				}
			}
			// 1,2,3,4,5,6,7;08:00
			putPowerParam(POWER_ON, powerOn);
			putPowerParam(POWER_OFF, powerOff);
			// 执行设置运行
			setPowerRunTime();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void setLocalRuntime(String powerOn, String powerOff) {
		if (powerOn != null && !powerOn.isEmpty() && powerOff != null && !powerOff.isEmpty()) {
			putPowerParam(POWER_ON, "1,2,3,4,5,6,7;" + powerOn);
			putPowerParam(POWER_OFF, "1,2,3,4,5,6,7;" + powerOff);
		} else {
			putPowerParam(POWER_ON, "");
			putPowerParam(POWER_OFF, "");
		}
		// 执行设置运行
		setPowerRunTime();
	}

	/**
	 * 设置开关机时间 android.os.Build.DEVICE=sugar-adtv
	 */
	public static void setRuntime(Date onTime, Date offTime) {
		Intent intent = new Intent("android.56iq.intent.action.setpoweronoff");
		boolean isEnable = false;
		if (onTime != null && offTime != null) {
			SimpleDateFormat yyyy_MM_dd_HH_mm = new SimpleDateFormat("yyyy_MM_dd_HH_mm");
			String[] onTimeString = yyyy_MM_dd_HH_mm.format(onTime).split("_");
			String[] offTimeString = yyyy_MM_dd_HH_mm.format(offTime).split("_");
			int[] on = new int[5], off = new int[5];
			for (int i = 0; i < 5; i++) {
				on[i] = Integer.parseInt(onTimeString[i]);
				off[i] = Integer.parseInt(offTimeString[i]);
			}
			intent.putExtra("timeon", on);
			intent.putExtra("timeoff", off);
			isEnable = true;
		}
		intent.putExtra("enable", isEnable);
        APP.getAPP().sendBroadcast(intent);
	}

	/**
	 * 机器重启
	 */
	public static void restart() {
		Log.i("机器重启", "重启重启！！！！！！！！！！！！！！！");
		// OnOffTool.setEnabled((byte) 0, (byte) 1, (byte) 0, (byte) 1);
		execSuCmd("reboot");
	}

	private static void execSuCmd(String cmd) {
		Process process = null;
		DataOutputStream os = null;
		DataInputStream is = null;
		try {
			process = Runtime.getRuntime().exec("su");
			os = new DataOutputStream(process.getOutputStream());
			os.writeBytes(cmd + "\n");
			os.writeBytes("exit\n");
			os.flush();
			int aa = process.waitFor();
			is = new DataInputStream(process.getInputStream());
			byte[] buffer = new byte[is.available()];
			is.read(buffer);
			String out = new String(buffer);
			Log.i("tag", out + aa);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				if (is != null) {
					is.close();
				}
				process.destroy();
			} catch (Exception e) {
			}
		}
	}

	/**
	 * 设置机器的开关机时间
	 */
	public static void setPowerRunTime() {
		Long[] powerOn = getPowerTime(POWER_ON);
		Long[] powerOff = getPowerTime(POWER_OFF);

		// 如果开关机时间没有设置，就进行网络获取

		if (powerOn != null && powerOff != null) {

			Long offh = powerOff[0] * 24 + powerOff[1];
            Long offm = powerOff[2];

			// 0 23 26
			// onh:0 onm:1
			// 0 23 25
			// offh:23 offm:25
			Long onh = powerOn[0] * 24 + powerOn[1];
			Long onm = powerOn[2];

			if ((onh * 60 + onm) > (offh * 60 + offm)) {
				long offset = (onh * 60 + onm) - (offh * 60 + offm);
				onm = offset % 60;
				onh = offset / 60;
			}
            Log.e("time", "\"sugar-adtv\".equals(Build.DEVICE):" + ("sugar-adtv".equals(Build.DEVICE)));
			if ("sugar-adtv".equals(Build.DEVICE)) {
				Date offDate = new Date();
				offDate.setMinutes(offDate.getMinutes() + (offh.intValue() * 60) + offm.intValue());
				Date onDate = new Date();
				onDate.setTime(offDate.getTime());
				onDate.setMinutes(onDate.getMinutes() + (onh.intValue() * 60) + onm.intValue());
				setRuntime(onDate, offDate);
			} else {
				// 启动开关机
                Log.e("time", "设置开关机时间：onh：" + onh.byteValue() + " onm:" + onm.byteValue() + " offh：" + offh.byteValue() + "offm：" + offm.byteValue());
                OnOffTool.setEnabled(onh.byteValue(), onm.byteValue(), offh.byteValue(), offm.byteValue());
			}
		} else {
            Log.e("time", "没有找到开关机时间");
			if ("sugar-adtv".equals(Build.DEVICE)) {
				setRuntime(null, null);
			} else {
				OnOffTool.setDisabled();
			}
		}
	}

	/**
	 * 机器开机时候，判断是否需要到网络查询
	 */
	public static void machineStart() {
        Log.e("time", "定时开关机");
		Long[] powerOn = getPowerTime(POWER_ON);
		Long[] powerOff = getPowerTime(POWER_OFF);

		// 如果开关机时间没有设置，就进行网络获取
		if (powerOn != null && powerOff != null) {
			setPowerRunTime();
		} else {
			PowerOffTool.getPowerOffTime(HeartBeatClient.getDeviceNo());
            setPowerRunTime();
		}
	}

	/**
	 * 获取下一个开关机时间
	 *
	 * @param powerType
	 * @return
	 */
	public static Long[] getPowerTime(String powerType) {
		Long[] runTimeLong = null;

		// 获取当天星期几
		Date currentDate = new Date();
		Integer weekDay = getWeekDay(currentDate);

		// 获取时间
		String powerOn = getPowerParam(powerType);
		if (powerOn != null && !powerOn.equals("")) {
			// 判断是否存在运行策略
			String[] powerOnArray = powerOn.split(";");
			String runDate = powerOnArray[0];
			String runTime = powerOnArray[1];

			String[] timeDateArray = runTime.split(":");
			Date onDate = new Date();
			onDate.setHours(Integer.parseInt(timeDateArray[0]));
			onDate.setMinutes(Integer.parseInt(timeDateArray[1]));
			if (runDate.indexOf(weekDay.toString()) != -1) {// 如果当天是运行策略中包含的周期
				if (onDate.getTime() > currentDate.getTime()) {
					// 如果开机时间大于当前时间，就需要设置
					runTimeLong = formatDuring(onDate.getTime() - currentDate.getTime());
				} else {
					// 推迟到运行周期中的下一天的这个时间
					Integer betweenDay = getBetweenDay(runDate, weekDay);
					onDate.setDate(onDate.getDate() + betweenDay);
					runTimeLong = formatDuring(onDate.getTime() - currentDate.getTime());
				}
			} else {
				// 如果运行策略中没有这一天
				Integer nextDay = getNextDay(runDate, weekDay);
				onDate.setDate(onDate.getDate() + nextDay);
				runTimeLong = formatDuring(onDate.getTime() - currentDate.getTime());
			}
		}
		return runTimeLong;
	}

	public static Integer getNextDay(String runDate, Integer currentWeekDay) {
		Integer between = 0;
		String[] runDateArray = runDate.split(",");
		for (int i = 0; i < runDateArray.length; i++) {
			Integer runDateA = Integer.parseInt(runDateArray[i]);
			if (runDateA > currentWeekDay) {
				between = runDateA - currentWeekDay;
				break;
			}
		}
		return between;
	}

	public static Integer getBetweenDay(String runDate, Integer currentWeekDay) {
		Integer between = 0;
		String[] runDateArray = runDate.split(",");
		for (int i = 0; i < runDateArray.length; i++) {
			Integer runDateA = Integer.parseInt(runDateArray[i]);
			if (runDateA == currentWeekDay) {
				if (i == runDateArray.length - 1) {
					between = Integer.parseInt(runDateArray[0]) + (7 - currentWeekDay);
				} else {
					runDateA = Integer.parseInt(runDateArray[i + 1]);
					between = runDateA - currentWeekDay;
				}
				break;
			}
		}
		return between;
	}

	/**
	 * 获取时间间隔
	 *
	 * @param mss
	 * @return
	 */
	public static Long[] formatDuring(Long mss) {
		long days = mss / (1000 * 60 * 60 * 24);
		long hours = (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
		long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60);
		long seconds = (mss % (1000 * 60)) / 1000;
		return new Long[] { days, hours, minutes, seconds };
	}

	public static void putPowerParam(String key, String value) {
		ACache acache = ACache.get(new File(FileConstants.PROPERTY_CACHE_PATH));
		acache.put(key, value);
	}

	/**
	 * @return 1,2,3,4,5,6,7;08:00
	 */
	public static String getPowerParam(String key) {
		ACache acache = ACache.get(new File(FileConstants.PROPERTY_CACHE_PATH));
		return acache.getAsString(key);
	}

	public static Integer getWeekDay(Date date) {
		SimpleDateFormat dateFm = new SimpleDateFormat("EEEE");
		String weekDay = dateFm.format(date);
		Integer week = 0;
		if (weekDay.equals("星期一")) {
			week = 1;
		} else if (weekDay.equals("星期二")) {
			week = 2;
		} else if (weekDay.equals("星期三")) {
			week = 3;
		} else if (weekDay.equals("星期四")) {
			week = 4;
		} else if (weekDay.equals("星期五")) {
			week = 5;
		} else if (weekDay.equals("星期六")) {
			week = 6;
		} else if (weekDay.equals("星期日")) {
			week = 7;
		}
		return week;
	}

	/**
	 * 机器重启
	 */
	public static void powerReload() {
		String cmd = "su -c reboot";
		try {
			Runtime.getRuntime().exec(cmd);
		} catch (IOException e) {
		}
	}

	/**
	 * 机器关机
	 */
	public static void powerShutdown() {
		try {
			Process process = Runtime.getRuntime().exec("su");
			DataOutputStream out = new DataOutputStream(process.getOutputStream());
			out.writeBytes("reboot -p\n");
			out.writeBytes("exit\n");
			out.flush();
		} catch (IOException e) {

		}
	}
}
